package algorithm.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import algorithm.model.dao.AnswerDao;
import algorithm.model.dao.MissionDao;
import algorithm.model.dao.TeamDao;
import algorithm.model.vo.Result;

public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final String ADMINISTRATION_PASSWORD = "admin2014";

	private TeamDao tdao;
	private MissionDao mdao;
	private AnswerDao adao;

	@Override
	public void init() throws ServletException {
		tdao = new TeamDao();
		mdao = new MissionDao();
		adao = new AnswerDao();
		super.init();
	}

	/** action 값을 받아 관리자용 process 선택 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("euc-kr");
		response.setCharacterEncoding("euc-kr");

		String action = request.getParameter("action");
		System.out.println("#adminProcess. selected action : " + action);

		if (action == null) {
			main(request, response);
		} else if (action.equals("login")) {
			login(request, response);
		} else if (action.equals("missionList")) {
			missionList(request, response);
		} else if (action.equals("resultList")) {
			resultList(request, response);
		} else if (action.equals("adminReset")) {
			adminReset(request, response);
		} else if (action.equals("resultPrint")) {
			resultPrint(request, response);
		} else if (action.equals("logout")) {
			logout(request, response);
		} else {
			main(request, response);
		}
	}

	/** 관리자 초기화면으로 이동 */
	public void main(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("page", "/WEB-INF/view/admin/main.jsp");
		request.getRequestDispatcher("/WEB-INF/view/admin/index.jsp").forward(request, response);
	}

	/** adminLogin.jsp : 관리자용 id 확인, 세션 저장 후 adminMain으로 이동 */
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=euc-kr");
		HttpSession session = request.getSession();
		String password = request.getParameter("password");
		
		System.out.println("#adminLogin02. tried");
		if (password.equals(ADMINISTRATION_PASSWORD)) {
			System.out.println("#adminLogin03. password matched");
			session.setAttribute("id", "admin");
			request.setAttribute("page", "/WEB-INF/view/admin/main.jsp");
		} else {
			System.out.println("#adminLogin04. password mismatched");
			request.setAttribute("errorMsg", "��й�ȣ�� Ʋ�Ƚ��ϴ�.");
			request.setAttribute("page", "/WEB-INF/view/admin/login.jsp");
		}
		
		request.getRequestDispatcher("/WEB-INF/view/admin/index.jsp").forward(request, response);
	}

	/** adminMenu.jsp : 미션 목록 로딩 후 missionList 표시 (missionDao 연동) */
	public void missionList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=euc-kr");
		try {
			request.setAttribute("missionList", mdao.list());
			request.setAttribute("missionCount", mdao.count());
			request.setAttribute("page", "/WEB-INF/view/admin/missionList.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMsg", "미션 목록 로딩 중 에러 발생");
			request.setAttribute("page", "/WEB-INF/view/common/error.jsp");
		}
		request.getRequestDispatcher("/WEB-INF/view/admin/index.jsp").forward(request, response);
	}

	/** adminMenu.jsp : 팀 목록 로딩 후 teamList 표시 (teamDao 연동) */
	public void teamList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=euc-kr");
		try {
			request.setAttribute("teams", tdao.finalList());
			request.setAttribute("page", "/adminPages/teamList.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMsg", "팀 목록 로딩 중 에러 발생");
			request.setAttribute("page", "/WEB-INF/view/common/error.jsp");
		}
		request.getRequestDispatcher("/WEB-INF/view/admin/index.jsp").forward(request, response);
	}

	public void resultList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=euc-kr");
		try {
			ArrayList<Result> results = adao.listResult();
			request.setAttribute("resultList", results);
			request.setAttribute("resultCount", results.size());
			
			System.out.println("results : " + results.size() + "건의 집계결과 반환");
			request.setAttribute("page", "/WEB-INF/view/admin/resultList.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMsg", "결과 목록 로딩 중 에러 발생");
			request.setAttribute("page", "/WEB-INF/view/common/error.jsp");
		}
		request.getRequestDispatcher("/WEB-INF/view/admin/index.jsp").forward(request, response);
	}

	/** adminMenu.jsp : testMode 표시 */
	public void adminReset(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
//		response.setContentType("text/plain; charset=euc-kr");
//		HashMap<String, String> map = new HashMap<String, String>();
//		ObjectMapper mapper = new ObjectMapper();
//		try {
//			adao.adminReset();
//			tdao.adminReset();
//			map.put("data", "completed");
//		} catch (Exception e) {
//			map.put("data", "incompleted");
//			e.printStackTrace();
//		}
//		mapper.writeValue(response.getWriter(), map);
	}
	
	public void resultPrint(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		
		/* 데이터가 저장될 Excel파일명 생성 : 식별파일명_현재날짜 */
		String fileName = "algorithmFestival_" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xls";
		
		FileOutputStream fOut = null;
		try {
			/* 데이터베이스로부터 기록 데이터 목록과 인스턴스 수량 추출 */
			ArrayList<Result> resultList = adao.listResult();
			int count = resultList.size();

			/* Excel 및 Sheet 객체 생성 */
			XSSFWorkbook wb = new XSSFWorkbook();
			XSSFSheet sheet = wb.createSheet();
			
			/* 최상단 칼럼 생성 */
			Row r = sheet.createRow(0);
			r.createCell(0).setCellValue("순위");
			r.createCell(1).setCellValue("팀 아이디");
			r.createCell(2).setCellValue("팀명");
			r.createCell(3).setCellValue("소속");
			r.createCell(4).setCellValue("총점");
			r.createCell(5).setCellValue("총 소요시간");
			
			/* 실제 데이터 입력 */
			for(int rowNum=1; rowNum<=count; rowNum++){
				Result rs = resultList.get(rowNum-1);
							
				r = sheet.createRow(rowNum);
				r.createCell(0).setCellValue(rowNum);
				r.createCell(1).setCellValue(rs.getId());
				r.createCell(2).setCellValue(rs.getName());
				r.createCell(3).setCellValue(rs.getClassName());
				r.createCell(4).setCellValue(rs.getSumScore());
				r.createCell(5).setCellValue(rs.getTimeSpent());
			}
			
			/* 데이터가 입력된 Sheet 객체를 물리적인 파일로 쓰기 */
			fOut = new FileOutputStream(new File("c:\\" + fileName));
			wb.write(fOut);
			
			System.out.println("results : " + count + "건에 대한 물리적 문서화 완료");
			request.setAttribute("page", "/WEB-INF/view/admin/main.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMsg", "엑셀 파일 추출 중 에러 발생");
			request.setAttribute("page", "/WEB-INF/view/common/error.jsp");
		} finally { 
			try {
				if(fOut != null) fOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		request.getRequestDispatcher("/WEB-INF/view/admin/index.jsp").forward(request, response);
	}	
	
	/** adminMenu.jsp : 세션 저장된 id 정보 삭제 후 adminLogin으로 이동 */
	public void logout(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("id");
		request.setAttribute("page", "/WEB-INF/view/user/login.jsp");
		request.getRequestDispatcher("/WEB-INF/view/admin/index.jsp").forward(request, response);
	}

}
